import { doFetch, postFetch } from "@/utils/doFetch";
import { LockOutlined, UserOutlined, MobileOutlined } from "@ant-design/icons";
import {
  LoginForm,
  ProFormCheckbox,
  ProFormText,
  ProFormCaptcha,
} from "@ant-design/pro-components";
import { history, useModel, useOutletContext } from "umi";
import {
  Progress,
  Dropdown,
  message,
  Tabs,
  Segmented,
  theme,
  Row,
  Col,
  Form,
} from "antd";
import { useRef, useState } from "react";
import IconFont from "@/components/IconFont";
import styles from "./index.less";
import zxcvbn from "zxcvbn";

const Loginpage = () => {
  const {
    initialState: { fetchUserInfo },
    setInitialState,
  } = useModel("@@initialState");
  const {
    token: { colorBgContainer, colorTextBase },
  } = theme.useToken();

  const { mode } = useOutletContext();

  const handleSubmit = async (values) => {
    if (loginType === "account") {
      // 登录
      const msg = await doFetch({
        url: "/user_token",
        params: {
          phone: values?.phone,
          password: values?.password,
        },
      });

      if (msg.jwt) {
        localStorage.setItem("TOKENSTRING", msg?.jwt);
        const currentUser = await fetchUserInfo();
        await setInitialState((s) => {
          return {
            ...s,
            currentUser,
          };
        });
        history.push("/dashboard");
      }
    } else {
      // 注册
      const msg = await postFetch({
        url: "/company/register",
        params: {
          name: values?.name,
          phone: values?.phone,
          code: values?.code,
          password: values?.password,
        },
      });
      if (msg.code === 0) {
        setLoginType("account");
      }
    }
  };

  const [loginType, setLoginType] = useState("account");
  const [type, settype] = useState("1");

  const [pwd, setPwd] = useState(null);

  const watchStrength = () => {
    const analysisValue = zxcvbn(pwd);
    // score得分只有0~4，且只有整数范围并没有小数
    return (analysisValue.score + 1) * 20;
  };

  return (
    <div
      className="noline"
      style={{
        width: 400,
        maxWidth: "calc(100vw - 16vw)",
        overflow: "hidden",
        position: "fixed",
        right: "8vw",
        top: "20vh",
        marginTop: "-2%",
        zIndex: 9999,
        backgroundColor:
          mode === "light" ? "rgba(255,255,255,0.9)" : "rgba(0,0,0,0.6)",
        borderRadius: 8,
        color: colorTextBase,
      }}
    >
      <div
        style={{
          flex: "1",
          paddingBottom: 24,
        }}
      >
        <h2 style={{ margin: "36px 0 -8px 36px", fontSize: 24 }}>
          欢迎使用
          <br />
          <span style={{ fontSize: 14 }}>WELCOME TO USE</span>
        </h2>
        <LoginForm
          logo={false}
          initialValues={{
            autoLogin: true,
          }}
          onFinish={async (values) => {
            await handleSubmit(values);
          }}
          submitter={{
            searchConfig: {
              submitText:
                loginType === "account"
                  ? "登录"
                  : type === "1"
                  ? "公司注册"
                  : "个人注册",
            },
          }}
          onValuesChange={(val) => {
            if (Object.keys(val)?.[0] === "password") {
              setPwd(Object.values(val)?.[0]);
            }
          }}
        >
          {/* <div style={{ height: 0, overflow: "hidden" }}>
            <input type="text" style={{ display: 'none' }} />
            <input type="password" style={{ opacity: '0' }} />
          </div> */}

          <Tabs
            activeKey={loginType}
            onChange={(activeKey) => setLoginType(activeKey)}
            items={[
              { label: "登录", key: "account" },
              { label: type === "1" ? "公司注册" : "个人注册", key: "phone" },
            ]}
            tabBarExtraContent={
              loginType == "phone" && (
                <Segmented
                  style={{ borderRadius: 60 }}
                  value={type}
                  onChange={settype}
                  options={[
                    {
                      value: "1",
                      icon: <IconFont type="icon-company" />,
                    },
                    {
                      value: "2",
                      icon: <UserOutlined />,
                    },
                  ]}
                />
              )
            }
          ></Tabs>

          {loginType === "account" && (
            <>
              <ProFormText
                name="phone"
                fieldProps={{
                  size: "large",
                  prefix: <MobileOutlined />,
                }}
                placeholder={"手机号"}
                rules={[
                  {
                    required: true,
                    message: "请输入手机号!",
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: "large",
                  prefix: <LockOutlined />,
                }}
                placeholder={"密码"}
                rules={[
                  {
                    required: true,
                    message: "请输入密码！",
                  },
                  
                ]}
              />
              <div
                style={{
                  marginBottom: 24,
                }}
              >
                <ProFormCheckbox noStyle name="autoLogin">
                  自动登录
                </ProFormCheckbox>
                <Dropdown
                  trigger={"click"}
                  placement="right"
                  dropdownRender={() => (
                    <div className="diycard" style={{ marginTop: -128 }}>
                      <img
                        src="./WechatIMG.jpeg"
                        alt=""
                        style={{ width: 240, margin: "2px 0 -2px 0" }}
                      />
                    </div>
                  )}
                >
                  <a
                    style={{
                      float: "right",
                    }}
                  >
                    忘记密码
                  </a>
                </Dropdown>
              </div>
            </>
          )}

          {loginType === "phone" && (
            <>
              {type == "1" && (
                <ProFormText
                  name="name"
                  fieldProps={{
                    size: "large",
                    prefix: <IconFont type="icon-company" />,
                  }}
                  placeholder={"公司名称"}
                  rules={[
                    {
                      required: true,
                      message: "请输入公司名称!",
                    },
                  ]}
                />
              )}

              <ProFormText
                name="phone"
                fieldProps={{
                  size: "large",
                  prefix: <MobileOutlined />,
                }}
                placeholder={"手机号"}
                rules={[
                  {
                    required: true,
                    message: "请输入手机号!",
                  },
                ]}
              />
              <ProFormCaptcha
                phoneName="phone"
                name="code"
                captchaProps={{
                  size: "large",
                }}
                fieldProps={{
                  size: "large",
                }}
                onGetCaptcha={async (phone) => {
                  message.success(`手机号 ${phone} 验证码发送成功!`);
                }}
                placeholder="请输入验证码"
                rules={[
                  {
                    required: true,
                    message: "请输入验证码",
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: "large",
                  prefix: <LockOutlined />,
                }}
                placeholder={"密码"}
                rules={[
                  {
                    required: true,
                    message: "请输入密码！",
                  },
                  {
                    pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=(?:\D*\d){3})(?=.*[$@$!%*?~.^-_+=&])[A-Za-z\d$@$!%*?&]{8,}/,
                    message: "至少包含八个字符，一个大写字母，一个小写字母，三个数字和一个特殊字符"
                  }
                ]}
              />
              {/* 显示密码强度 */}

              <div className={styles["process-steps"]}>
                <Progress
                  percent={pwd ? watchStrength() : 0}
                  steps={5}
                  strokeColor={[
                    "#e74242",
                    "#EFBD47",
                    "#ffa500",
                    "#1bbf1b",
                    "#008000",
                  ]}
                  showInfo={false}
                />
              </div>
              <Row justify="space-around">
                {["非常弱", "弱", "一般", "强", "非常强"].map((value) => (
                  <Col span={4} key={value} className="center">
                    {value}{" "}
                  </Col>
                ))}
              </Row>

              <ProFormText.Password
                name="confirm"
                dependencies={["password"]}
                fieldProps={{
                  size: "large",
                  prefix: <LockOutlined />,
                }}
                placeholder={"确认密码"}
                style={{marginTop:12}}
                rules={[
                  {
                    required: true,
                    message: "请输入密码！",
                  },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!value || getFieldValue("password") === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error("两次密码不一致!"));
                    },
                  }),
                ]}
              />
            </>
          )}
        </LoginForm>
      </div>
    </div>
  );
};

export default Loginpage;
